#include <iostream>

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>

#include "ascii_logo.h"
#include "session.hpp"

#include "luoo_tcp_server.hpp"
#include "luoo_mysql_database.hpp"
#include "luoo_mysql_recordset.hpp"

#ifdef WIN32
#	pragma comment(lib, "libmysql.lib")
#endif

int main(const int argc, const char* argv[])
{
	int n = sizeof(ascii_logo) / sizeof(ascii_logo[0]);
	for (int i = 0; i < n; ++i)
	{
		std::cout << ascii_logo[i];
	}

//	SYSTEM_INFO si = {0};
//	GetSystemInfo(&si);
//	int processor = si.dwNumberOfProcessors * 2 + 2;
	int processor = 4;

	sMySQLDB.init(processor);
	if (!sMySQLDB.connect("localhost", 3306, "root", "145286", "pcikbot"))
	{
		sMySQLDB.disconnect();
		std::cerr << "connect db failed!" << std::endl;
//		return -1;
	}

	luoo::tcp_server<session>* server = new luoo::tcp_server<session>(processor);
	if (!server->start("192.168.0.103", 6666))
	{
		sMySQLDB.disconnect();
		std::cerr << "server start failed!" << std::endl;
		return -1;
	}
	
	std::cout << "server started!" << std::endl;

#ifdef __GNUC__

	if(2 == argc)
	{
		if(!strcmp("-fork",argv[1]))
		{
			pid_t pid = fork();
			if(pid < 0)
			{
				std::cerr << "fork failed!" << std::endl;
				return -1;
			}
			else if (pid > 0)
			{
				return 0;
			}
			setsid();
			int fd = open("/dev/null",O_RDWR, 0);
			if (- 1== fd)
			{
				std::cerr << "open /dev/null failed!" << std::endl;
				return -1;
			}
			if (-1 != fd)
			{
				dup2(fd,STDIN_FILENO);
				dup2(fd,STDOUT_FILENO);
				dup2(fd,STDERR_FILENO);
				close(fd);
			}
		}
	}

#endif

	std::string input;
	while(true)
	{
		std::cin >> input;
		if (input == "exit")
		{

			break;
		}
	}

	server->stop();

	delete server;
	sMySQLDB.disconnect();

	return 0;
}